<?php

namespace App\Utils;

use App\Constants\Common\AppCode;
use Hyperf\Framework\Logger\StdoutLogger;
use Hyperf\Logger\LoggerFactory;
use Psr\Log\LoggerInterface;

class PrintLogger
{

    /**
     * @var LoggerInterface
     */
    protected static $logger;

    /**
     * @param mixed $info 要打印的信息
     * @param array|string $tag
     * @param int $level 3:error, 2:warning, 1:info
     * @return void
     */
    public static function dump($info, string|array $tag='', $level=1)
    {
        $dataType = 'type-'.gettype($info);
        $tag = self::arrTag($tag);
        $tag[] = $dataType;
        if (is_array($info)){
            $info = json_encode($info,320);
        }elseif (is_object($info)){
            $info = var_export($info,true);
        }

        if ($level == 1){
            self::info($info, $tag);
        }elseif ($level == 2){
            self::warning($info, $tag);
        }else{
            self::error($info, $tag);
        }
    }

    /**
     * @param $tag
     * @return array
     */
    protected static function arrTag($tag)
    {
        if (empty($tag)){
            return [];
        }
        if (is_string($tag)){
            $fTag[] = $tag;
        }else{
            $fTag = $tag;
        }
        return $fTag;
    }

    protected static function handleTag(array $tag=[])
    {
        $stdTag = '';
        $logTag = '';
        if (!empty($tag)) {
            foreach ($tag as $t){
                $stdTag .= '<fg=red>['.$t.']</> ';
                $logTag .= '['.$t.'] ';
            }
        }
        return [$stdTag, $logTag];
    }

    protected static function error(string $info, array $tag=[])
    {
        [$stdTag, $logTag] = self::handleTag($tag);
        make(StdoutLogger::class)->error($stdTag.$info);
        self::getLogger()->error($logTag.$info);
    }

    protected static function info(string $info, array $tag=[])
    {
        [$stdTag, $logTag] = self::handleTag($tag);
        make(StdoutLogger::class)->info($stdTag.$info);
        self::getLogger()->info($logTag.$info);
    }

    protected static function warning(string $info, array $tag=[])
    {
        [$stdTag, $logTag] = self::handleTag($tag);
        make(StdoutLogger::class)->warning($stdTag.$info);
        self::getLogger()->warning($logTag.$info);
    }

    protected static function getLogger()
    {
        if (self::$logger){
            return self::$logger;
        }
        self::$logger = make(LoggerFactory::class)->get('log');
        return self::$logger;
    }
}